



const express = require('express');
const multer = require('multer');
const config = require('../../config')
const router = express.Router();


function checkFileExt(ext, rule = 'png|jpeg|bmp|jpg') {
    if (!ext) return false;
    return rule.includes(ext);
}

function fileFilter(req, file, cb) {
    let fileExt = file.originalname.split('.').pop();
    if (checkFileExt(fileExt)) {
        cb(null, true);
    } else {
        cb(null, false);
    }
}

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, config.uploadDriectory);
    },

    filename: function (req, file, cb) {
        let fileExt = file.originalname.split('.').pop();
        cb(null, `${Math.random()}_${(new Date()).getTime()}.${fileExt}`);
    }
})

var upload = multer({
    fileFilter,
    storage
})

router.post('/', upload.single('img'));

module.exports = router;